package com.tomato.study.rabbitmq.provider.service;

import com.tomato.study.rabbitmq.core.constant.RabbitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Locale;
import java.util.UUID;


/**
 * 生产者声明队列，并向队列发送消息
 *
 * @author lizhifu
 * @date 2022/3/21
 */
@Component
@Slf4j
public class RabbitSimpleSender {
    @Resource
    private RabbitTemplate rabbitTemplate;

    public void sendSimpleConfirmQueue(String msg) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString().toUpperCase(Locale.ROOT));
        rabbitTemplate.invoke(
                operations -> {
                    rabbitTemplate.convertAndSend(RabbitConstant.SIMPLE_QUEUE_NAME, (Object) msg, correlationData);
                    boolean waitForConfirms = false;
                    try {
                        waitForConfirms = rabbitTemplate.waitForConfirms(1);
                    } catch (Exception e) {
                       log.error("RabbitSimpleSender sendSimpleConfirmQueue Exception",e);
                    }
                    log.info("RabbitSimpleSender sendSimpleConfirmQueue waitForConfirms:{}",waitForConfirms);
                    return waitForConfirms;
                },
                // deliveryTag（唯一标识 ID）：它代表了 RabbitMQ 向该 Channel 投递的这条消息的唯一标识 ID，是一个单调递增的正整数。
                // multiple：批处理标志，当该参数为 true 时，则可以一次性确认 delivery_tag 小于等于传入值的所有消息。
                (deliveryTag, multiple) -> {
                    log.info("RabbitSimpleSender sendSimpleConfirmQueue deliveryTag：{}, multiple：{}", deliveryTag, multiple);
                },
                (deliveryTag, multiple) -> {
                    log.info("RabbitSimpleSender sendSimpleConfirmQueue deliveryTag：{}, multiple：{}", deliveryTag, multiple);
                }
        );
    }
    /**
     * 使用事务
     * @return
     */
    @Transactional(rollbackFor = Exception.class,transactionManager = "rabbitTransactionManager")
    public void sendSimpleTransactionQueue(int msg) {
        // 开始事务
        rabbitTemplate.setChannelTransacted(true);
        rabbitTemplate.convertAndSend(RabbitConstant.SIMPLE_QUEUE_TRANSACTION_NAME, "hello world!"+msg);
        if(msg == 1){
            throw new RuntimeException("事务测试");
        }
    }
}